package com.wr.recruit.service.service.impl;

import com.wr.recruit.service.dao.dbo.AttachmentDbo;
import com.wr.recruit.service.dao.dbo.DepartmentDbo;
import com.wr.recruit.service.dao.dbo.MailDbo;
import com.wr.recruit.service.dao.dbo.UserDbo;
import com.wr.recruit.service.dao.repo.AttachmentRepo;
import com.wr.recruit.service.dao.repo.MailRepo;
import com.wr.recruit.service.dao.repo.UserRepo;
import com.wr.recruit.service.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.persistence.criteria.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Properties;

@Service
public class MailServiceImpl implements MailService {

    private MailRepo mailRepo;
    private UserRepo userRepo;
    private AttachmentRepo attachmentRepo;

    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.port}")
    private String port;

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;

    @Autowired
    public MailServiceImpl(MailRepo mailRepo, UserRepo userRepo, AttachmentRepo attachmentRepo) {
        this.mailRepo = mailRepo;
        this.userRepo = userRepo;
        this.attachmentRepo = attachmentRepo;
    }

    @Override
    public String sendMail(String mailCode,Integer step, String sender, String accepter, String attachmentCode, String subject, String content) throws Exception {
        UserDbo allByUserName = userRepo.findAllByUserName(accepter);
        AttachmentDbo allByAttachmentCode = attachmentRepo.findAllByAttachmentCode(attachmentCode);
        ZoneId zoneId = ZoneId.systemDefault();
        Timestamp time = new Timestamp(new Date().getTime());

        Properties properties = new Properties();
        //设置smtp协议
        properties.put("mail.transport.protocol", "SMTP");
        //设置服务器连接地址
        properties.put("mail.smtp.host", host);
        //设置TLS保护连接，默认为false
        properties.put("mail.smtp.starttls.enable", "true");
        //设置身份校验
        properties.put("mail.smtp.auth", "true");
        //设置默认端口号
        properties.put("mail.smtp.port", port);
        //不做服务器证书校验
        properties.put("mail.smtp.ssl.checkserveridentity", "false");
        //信任全部
        properties.put("mail.smtp.ssl.trust", "*");
        //使用环境属性和授权信息，创建邮件会话
        Session session = Session.getInstance(properties);
        //创建邮件消息
        MimeMessage msg = new MimeMessage(session);
        MimeMessageHelper helper = new MimeMessageHelper(msg, true);
        helper.setFrom(username);
        String[] split;
        String mails = allByUserName.getMail();
        if(mails.contains(";")){
            split = mails.split(";");
            helper.setTo(split);
        }else if(mails.contains(",")){
            split = mails.split(",");
            helper.setTo(split);
        }else{
            helper.setTo(mails);
        }
        helper.setSubject(subject);
        helper.setText(content);
        if(allByAttachmentCode.getFilePath() != null && !allByAttachmentCode.getFilePath().isEmpty()){
            FileSystemResource file = new FileSystemResource(allByAttachmentCode.getFilePath());
            if(!file.exists()){
                throw new Exception();
            }
            helper.addAttachment(allByAttachmentCode.getFileName(), file);//添加附加
        }
        //建立邮件传输对象
        Transport transport = session.getTransport("smtp");
        //与服务端建立连接
        transport.connect(host,username, password);
        //发送邮件
        transport.sendMessage(msg, msg.getAllRecipients());
        //关闭
        transport.close();

        MailDbo mail = new MailDbo(mailCode,subject,content,sender,accepter,attachmentCode,step,time);
        mailRepo.save(mail);

        return "success";
    }

    @Override
    public Page<MailDbo> getMailListInfo(String userName, Integer pageSize, Integer pageNum) {
        Specification<MailDbo> specification = new Specification<MailDbo>() {
            @Override
            public Predicate toPredicate(Root<MailDbo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate p1 = cb.like(root.get("accepter").as(String.class), "%"+userName+"%");
                query.where(p1);
                return query.getRestriction();
            }
        };
        return mailRepo.findAll(specification,new PageRequest(pageNum - 1, pageSize));
    }

    @Override
    public MailDbo getMailInfo(String mailCode, Integer step) {
        return mailRepo.findAllByMailCodeAndStep(mailCode, step);
    }
}
